using System;
using System.Collections;

namespace fuzzyKittenVNC
{

	public class WebSocketResponse
	{
		WebSocketHeader header;
		byte[] payload;
		bool secure = false;
		
		
		public WebSocketResponse(WebSocketHeader header, byte[] payload,bool secure) {
			this.header = header;
			this.payload = payload;
			this.secure = secure;
		}	
		
		public string GetString() {
			string result = "";
			result += System.Text.Encoding.UTF8.GetString(this.getHeaderString());
			if(payload != null && payload.Length >0)
				result += "\r\n"+System.Text.Encoding.UTF8.GetString(payload);
			return result;
		}
		
		public byte[] getHeaderString() {
			string headerString = "";
			byte[] intermediate_result;
			byte[] result;
			switch(this.header.type) {
				case WebSocketHeader.HEADER_TYPE.HANDSHAKE_REQUEST:
					headerString += "GET / HTTP/1.1\r\n";
					break;
				case WebSocketHeader.HEADER_TYPE.HANDSHAKE_RESPONSE:
					headerString += "HTTP/1.1 101 Web Socket Protocol Handshake\r\n";
					break;
				default:
					break;
			}
			foreach(string headerVar in header.getHeaders()) {
				ArrayList variables = header.getHeader(headerVar);
				foreach(String varValue in variables) {
					headerString += String.Format("{0}: {1}\r\n",headerVar,varValue);
				}
			}
			headerString += "\r\n";
			intermediate_result = System.Text.Encoding.UTF8.GetBytes(headerString);
			result = new byte[intermediate_result.Length+header.keyAppendix.Length];
			intermediate_result.CopyTo(result,0);
			if(this.header.type == WebSocketHeader.HEADER_TYPE.HANDSHAKE_REQUEST ||
				this.header.type == WebSocketHeader.HEADER_TYPE.HANDSHAKE_RESPONSE) {
				header.keyAppendix.CopyTo(result,result.Length-header.keyAppendix.Length);
			}
			
			return result;
		}
		
		public void fillFromRequestHeader(WebSocketHeader reqHeader) {
			if(reqHeader.getHeader("Origin").Count > 0) {
				string origin = (string) reqHeader.getHeader("Origin")[0];
				this.header.addHeader("Sec-WebSocket-Origin", origin);
			}
			
			if(reqHeader.getHeader("Host").Count > 0) {
				string host = (string)reqHeader.getHeader("Host")[0];
				string ws = (this.secure ? "wss" : "ws")+"://"+host+reqHeader.ressource; 
				this.header.addHeader("Sec-WebSocket-Location",ws);	
			}
			
			if(reqHeader.getHeader("Sec-WebSocket-Protocol").Count > 0) {
				string protocol = (string) reqHeader.getHeader("Sec-WebSocket-Protocol")[0];
				this.header.addHeader("Sec-WebSocket-Protocol",protocol);
			}
		}
	}
}

